<template>
  <van-loading size="20" v-if="isLoading" />
  <van-icon
    v-else
    :color="isCollect ? '#ffa500' : '#777'"
    :name="isCollect ? 'star' : 'star-o'"
    @click="onCollect"
  />
</template>

<script>
import { addCollect, delCollect } from '@/api/article'
export default {
  props: ['article'],
  data () {
    return {
      isCollect: false,
      isLoading: false
    }
  },

  created () {
    this.isCollect = this.article.is_collected
  },

  methods: {
    async onCollect () {
      this.isLoading = true
      try {
        if (!this.isCollect) {
          // 未收藏 点击添加收藏
          await addCollect(this.article.art_id)
          this.$toast('收藏成功！')
          this.isCollect = true
        } else {
          // 已收藏 点击取消收藏
          await delCollect(this.article.art_id)
          this.$toast('取消收藏成功！')
          this.isCollect = false
        }
      } catch (error) {
        this.$toast('发生了一个错误，请稍后再试！')
      }
      this.isLoading = false
    }
  }
}
</script>

<style scoped lang="less">
.van-loading {
  font-size: 10px;
}
</style>
